package cn.tml.innermost.music.utils;

import cn.tml.innermost.music.entity.pachong.JsonRootBean;
import com.alibaba.fastjson.JSON;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.utils.HttpConstant;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;


// 构造QQ音乐综合请求url工具类
public class QQMusicRequest {

    private final static String qqUrlPrefix = "https://u.y.qq.com/cgi-bin/musics.fcg?_=%s&sign=%s";

    private static String script = "";

    // 一次性加载js成解密函数
    static {
        try {
            InputStream inputStream = QQMusicRequest.class.getClassLoader().getResourceAsStream("sign.js");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            script = sb.toString();
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 通过json对象构造sign
    private static String getSign(String data) {
        try {
            // Initialize JavaScript Engine
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("graal.js");
            engine.eval(script);

            // Call the get_sign function
            Invocable invocable = (Invocable) engine;

            return (String) invocable.invokeFunction("get_sign", data);
        } catch (ScriptException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    // 通过json字符串得到url
    private static String getQQMusicUrl(String data) {
        String sign = getSign(data);
        String timestamp = String.valueOf(System.currentTimeMillis());
        return String.format(qqUrlPrefix, timestamp, sign);
    }

    // 通过JsonRootBean得到Request对象
    public static Request getQQMusicRequest(JsonRootBean jsonRootBean) {
        String jsonStr = JSON.toJSONString(jsonRootBean);
        String qqMusicUrl = QQMusicRequest.getQQMusicUrl(jsonStr);
        Request request = new Request(qqMusicUrl);
        request.setMethod(HttpConstant.Method.POST);
        request.setRequestBody(HttpRequestBody.json(jsonStr, "utf-8"));
        return request;
    }


}
